/*
 * Copyright (c) 2020, 2023, 3044483124@qq.com All rights reserved.
 *
 */
package cn.itcast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * <p>Project: JavaStudy - Dir7
 * <p>Powered by jiangbo On 2023-01-03
 * 21:26:39
 * <p>Created by IntelliJ IDEA
 *
 * @author jiangbo [3044483124@qq.com]
 * @version 1.0
 * @since 8/17
 */
public class Dir7 {
    public static void main(String[] args) {
//实现目录复制，此方法也可以实现文件复制功能
//copy(new File("f1.txt"), new File("abc.txt"));
        copy(new File("C:\\Users\\30444\\Desktop\\截图\\wang_001.png"),new File("users/001.png"));
//copy(new File("c:/tmp/aa.jpg"),new File("users/yy.jpg"));
    }
    public static void copy(File src, File dst) {
        if (src.isDirectory()) {
            if (!dst.exists()) {
                dst.mkdirs();
            }
            for (File f : src.listFiles()) {
                if (f.isDirectory()) {
//递归复制目录
                    copy(f, new File(dst + "/" + f.getName()));
                }
//文件复制
                if (f.isFile()) {
                    copy(f, new File(dst.getAbsoluteFile() + "/" + f.getName()));
                }
            }
        }
//文件复制
        if(src.isFile()) {
            if(!dst.exists()){
                String fn = dst.getAbsolutePath();
                System.out.println(fn);
                String path = fn.substring(0,fn.lastIndexOf(File.separator));
                File tm = new File(path);
                tm.mkdirs();
            }
            try (var fis = new FileInputStream(src);
                 var fos = new FileOutputStream(dst.getAbsoluteFile()))
            {
                fis.transferTo(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}


